package com.wnhz.work.yz.wheel;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.activity.AlertActivity;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.wnhz.work.yz.view.ShowAlertDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


public class AlertAddress extends AlertActivity implements View.OnClickListener, OnWheelChangedListener {
    private WheelView mViewProvince;
    private WheelView mViewCity;
    private WheelView mViewDistrict;
    private TextView mBtnConfirm, mBtnCancel;

    private String from;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alert_address);

//        findViewById(R.id.alert_root).getBackground().setAlpha(100);
        initData();
        setUpViews();
        setUpListener();
        setUpData();
    }

    private void initData() {
        from = getIntent().getStringExtra("from");
    }

    private void setUpViews() {
        mViewProvince = (WheelView) findViewById(R.id.id_province);
        mViewCity = (WheelView) findViewById(R.id.id_city);
        mViewDistrict = (WheelView) findViewById(R.id.id_district);
        mBtnConfirm = (TextView) findViewById(R.id.tv_wheel_ok);
        mBtnCancel = (TextView) findViewById(R.id.tv_wheel_cancel);

        mBtnCancel.setOnClickListener(this);
        mBtnConfirm.setOnClickListener(this);
    }

    private void setUpListener() {
        // 添加change事件
        mViewProvince.addChangingListener(this);
        // 添加change事件
        mViewCity.addChangingListener(this);
        // 添加change事件
        mViewDistrict.addChangingListener(this);
        // 添加onclick事件
        mBtnConfirm.setOnClickListener(this);
    }

    private void setUpData() {
        initProvinceDatas();
        mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(AlertAddress.this, mProvinceDatas));
        // 设置可见条目数量
        mViewProvince.setVisibleItems(7);
        mViewCity.setVisibleItems(7);
        mViewDistrict.setVisibleItems(7);
        updateCities();
        updateAreas();
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        // TODO Auto-generated method stub
        if (wheel == mViewProvince) {
            updateCities();
        } else if (wheel == mViewCity) {
            updateAreas();
        } else if (wheel == mViewDistrict) {
            mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
            mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
        }
    }

    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        int pCurrent = mViewCity.getCurrentItem();
        mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
        String[] areas = mDistrictDatasMap.get(mCurrentCityName);

        if (areas == null) {
            areas = new String[]{""};
        }
        mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(this, areas));
        mViewDistrict.setCurrentItem(0);
        mCurrentDistrictName = areas[0];
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        int pCurrent = mViewProvince.getCurrentItem();
        mCurrentProviceName = mProvinceDatas[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null) {
            cities = new String[]{""};
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(this, cities));
        mViewCity.setCurrentItem(0);
        updateAreas();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_wheel_ok:
                showSelectedResult();
                if ("UserInfoManagerActivity".equals(from)) {
                    changeAddressMessage();
                }
                Intent intent = new Intent();
                intent.putExtra("address", mCurrentProviceName + "-"
                        + mCurrentCityName + "-" + mCurrentDistrictName);
                intent.putExtra("province", mCurrentProviceName);
                intent.putExtra("city", mCurrentCityName);
                intent.putExtra("district", mCurrentDistrictName);
                setResult(333, intent);
                finish();
                overridePendingTransition(R.anim.push_up_in, R.anim.push_down_out);
                break;

            case R.id.tv_wheel_cancel:

                finish();
                overridePendingTransition(R.anim.push_up_in, R.anim.push_down_out);
                break;
            default:
                break;
        }
    }

    private static final String TAG = "AlertAddress";

    private void changeAddressMessage() {
      //  showDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("province", mCurrentProviceName);
        map.put("city", mCurrentCityName);
        map.put("district", mCurrentDistrictName);
        Log.i(TAG, "onSuccess: city= " + mCurrentProviceName + "-"
                + mCurrentCityName + "-" + mCurrentDistrictName);
        XUtil.Post(Url.MEMBER_SETMEMBERINFO, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                closeDialog();
                super.onSuccess(result);
                Log.i(TAG, "onSuccess: city= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
//                    if ("-1".equals(res)) {
//                        //info = "请重新登录";
//                        MyToast("请重新登录");
//                        startActivity(new Intent(AlertAddress.this, LoginNewActivity.class));
//                        return;
//                    }
                    if ("1".equals(res)) {
                        MyToast(info);
                    } else {
                        MyToast(info);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });

    }

    private void showSelectedResult() {
//        Toast.makeText(AlertAddress.this, "当前选中:" + mCurrentProviceName + "," + mCurrentCityName + ","
//                + mCurrentDistrictName + "," + mCurrentZipCode, Toast.LENGTH_SHORT).show();
    }

    private Toast toast;

    public void MyToast(String s) {
        if (toast == null)
            toast = Toast.makeText(this, s, Toast.LENGTH_SHORT);
        else
            toast.setText(s);
        toast.show();
    }

    protected Dialog dialog;
    public void showDialog() {

        if (null == dialog) {
            dialog = ShowAlertDialog.loadingDialog(this);
        }
        dialog.show();
    }

    public void closeDialog() {
        if (null != dialog) {
            dialog.dismiss();
        }
    }
}